using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Services
{
    /// <summary>
    /// 天气服务实现类
    /// </summary>
    public class WeatherService : IWeatherService
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<WeatherService> _logger;
        
        // 天气状况列表，用于生成模拟数据
        private static readonly string[] WeatherConditions = new[]
        {
            "晴天", "多云", "阴天", "小雨", "中雨", "大雨", "雷阵雨", "雾天", "霾"
        };

        public WeatherService(HttpClient httpClient, ILogger<WeatherService> logger)
        {
            _httpClient = httpClient;
            _logger = logger;
        }

        /// <summary>
        /// 根据地区名称获取当前天气信息
        /// </summary>
        /// <param name="regionName">地区名称</param>
        /// <returns>天气信息</returns>
        public async Task<WeatherInfo> GetWeatherByRegionAsync(string regionName)
        {
            _logger.LogInformation("获取地区天气信息 - 地区: {Region}", regionName);
            
            try
            {
                // 实际项目中，这里应该调用真实的天气API
                // 由于是示例，我们返回模拟数据
                // 以下是实际调用天气API的注释代码
                
                /*
                // 构造天气API请求URL
                var apiUrl = $"https://api.weather.com/v1/weather?region={regionName}&key=your_api_key";
                
                // 发送HTTP请求
                var response = await _httpClient.GetAsync(apiUrl);
                
                // 检查响应状态
                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogError("天气API调用失败: {StatusCode}", response.StatusCode);
                    throw new Exception($"天气API调用失败: {response.StatusCode}");
                }
                
                // 读取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                
                // 反序列化响应内容
                var weatherData = JsonConvert.DeserializeObject<WeatherApiResponse>(responseContent);
                
                // 转换为我们的WeatherInfo对象
                return new WeatherInfo
                {
                    RegionName = regionName,
                    CurrentTemperature = weatherData.CurrentTemperature,
                    WeatherCondition = weatherData.WeatherCondition,
                    FeelsLikeTemperature = weatherData.FeelsLikeTemperature,
                    Humidity = weatherData.Humidity,
                    WindSpeed = weatherData.WindSpeed,
                    UpdateTime = DateTime.Now
                };
                */
                
                // 返回模拟数据
                return GenerateMockWeatherData(regionName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气信息异常: {Message}", ex.Message);
                // 在异常情况下仍然返回模拟数据，确保接口可用性
                return GenerateMockWeatherData(regionName);
            }
        }

        /// <summary>
        /// 获取指定地区近七天的天气预报
        /// </summary>
        /// <param name="regionName">地区名称</param>
        /// <returns>近七天天气预报</returns>
        public async Task<List<WeatherForecast>> Get7DayWeatherForecastAsync(string regionName)
        {
            _logger.LogInformation("获取近七天天气预报 - 地区: {Region}", regionName);
            
            try
            {
                // 实际项目中，这里应该调用真实的天气API
                // 由于是示例，我们返回模拟数据
                // 以下是实际调用天气API的注释代码

                /*
                // 构造天气API请求URL
                var apiUrl = $"https://api.weather.com/v1/forecast/7day?region={regionName}&key=your_api_key";
                
                // 发送HTTP请求
                var response = await _httpClient.GetAsync(apiUrl);
                
                // 检查响应状态
                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogError("天气预报API调用失败: {StatusCode}", response.StatusCode);
                    throw new Exception($"天气预报API调用失败: {StatusCode}");
                }
                
                // 读取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                
                // 反序列化响应内容
                var forecastData = JsonConvert.DeserializeObject<ForecastApiResponse>(responseContent);
                
                // 转换为我们的WeatherForecast对象列表
                var forecasts = forecastData.Forecasts.Select(f => new WeatherForecast
                {
                    Date = f.Date,
                    MinTemperature = f.MinTemperature,
                    MaxTemperature = f.MaxTemperature,
                    WeatherCondition = f.WeatherCondition,
                    PrecipitationProbability = f.PrecipitationProbability
                }).ToList();
                
                return forecasts;
                */

                // 返回模拟数据
                return GenerateMockWeatherForecasts(regionName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取天气预报异常: {Message}", ex.Message);
                // 在异常情况下仍然返回模拟数据，确保接口可用性
                return GenerateMockWeatherForecasts(regionName);
            }
        }

        /// <summary>
        /// 生成模拟天气数据
        /// </summary>
        private WeatherInfo GenerateMockWeatherData(string regionName)
        {
            var random = new Random();
            
            return new WeatherInfo
            {
                RegionName = regionName,
                CurrentTemperature = random.Next(10, 35),
                WeatherCondition = WeatherConditions[random.Next(WeatherConditions.Length)],
                FeelsLikeTemperature = random.Next(10, 35),
                Humidity = random.Next(30, 95),
                WindSpeed = random.Next(0, 25),
                UpdateTime = DateTime.Now
            };
        }

        /// <summary>
        /// 生成模拟天气预报数据
        /// </summary>
        private List<WeatherForecast> GenerateMockWeatherForecasts(string regionName)
        {
            var random = new Random();
            var forecasts = new List<WeatherForecast>();
            
            for (int i = 0; i < 7; i++)
            {
                var date = DateTime.Now.AddDays(i);
                var minTemp = random.Next(10, 25);
                var maxTemp = minTemp + random.Next(5, 15);
                
                forecasts.Add(new WeatherForecast
                {
                    Date = date,
                    MinTemperature = minTemp,
                    MaxTemperature = maxTemp,
                    WeatherCondition = WeatherConditions[random.Next(WeatherConditions.Length)],
                    PrecipitationProbability = random.Next(0, 100)
                });
            }
            
            return forecasts;
        }
    }
}